package org.flown.novel.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.flown.novel.dao.AuthorDAO;
import org.flown.novel.dao.BookDAO;
import org.flown.novel.data.Author;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AuthorService
{

    @Autowired
    private AuthorDAO dao_author;
    @Autowired
    private BookDAO dao_book;

    private final QueryWrapper<Author> qw = new QueryWrapper<>();


    public Author getAuthorByID(int author_id)
    {
        this.qw.clear();
        this.qw.eq(Author.Column.ID.getName(), author_id);
        return this.dao_author.selectOne(qw);
    }

    public Author getAuthorByUserID(int user_id)
    {
        this.qw.clear();
        this.qw.eq(Author.Column.USER_ID.getName(), user_id);
        return this.dao_author.selectOne(qw);
    }

    public Author getAuthorByName(String pen_name)
    {
        this.qw.clear();
        this.qw.eq(Author.Column.NAME.getName(), pen_name);
        return this.dao_author.selectOne(qw);
    }


    /**
     * 此处没有检查用户存在与否，在调用前确保用户已经存在
     * <br>在LoginInterceptor或LoginInterceptor中拦截
     * */
    public ServiceResult register(int user_id, String pen_name)
    {
        if (pen_name == null || pen_name.equals(""))
            return ServiceResult.NULL_NAME;

        this.qw.clear();
        this.qw.eq(Author.Column.USER_ID.getName(), user_id);
        Author temp = this.dao_author.selectOne(this.qw);
        if (temp != null)
            return ServiceResult.REGISTERED;
        this.qw.clear();
        this.qw.eq(Author.Column.NAME.getName(), pen_name);
        temp = this.dao_author.selectOne(this.qw);
        if (temp != null)
            return ServiceResult.EXISTS_NAME;

        Author author = new Author(user_id, pen_name);
        if (this.dao_author.insert(author) == 0)
            return ServiceResult.FAILED;
        return ServiceResult.SUCCESS;
    }


}



